<!-- @format -->

<template>
 <view class="uno-h-screen uno-min-w-screen home-index home-page uno-overflow-hidden uno-flex uno-flex-col">
  <wd-sticky>
   <view class="uno-w-screen uno-bg-[#f8f8f8]">
    <wd-tabs v-model="tabValue" @change="tabChangeUpdateTaskList">
     <block v-for="item in taskTypeOptions" :key="item.value">
      <wd-tab :title="item.label">
       <view class="content uno-hidden">内容{{ item }}</view>
      </wd-tab>
     </block>
    </wd-tabs>
    <view class="uno-flex uno-flex-items-center uno-h-[44px] uno-p-x-[16px] uno-box-border uno-w-full uno-text-[14px] uno-w-full uno-tab-bar-item">
     <block v-for="item in taskTypeFilter" :key="item.value">
      <view class="uno-p-y-[6px] uno-p-x-[14px] uno-rounded-[4px] uno-bg-white uno-m-r-[16px]" :class="{ 'tab-bar-active': item.checked }" @click="filterTaskType(item)">{{ item.label }} </view>
     </block>
    </view>
   </view>
  </wd-sticky>
  <!-- 显示任务卡片 -->
  <wd-fab type="success" v-model:active="fabActive" activeIcon="add" :draggable="true"></wd-fab>
  <view v-if="!taskList.length">
   <wd-status-tip image="content" tip="暂无内容" />
  </view>
  <scroll-view v-else scroll-y class="uno-h-[80vh] uno-box-border uno-w-full task-view">
   <view class="uno-px-[16px] uno-p-b-[20px]">
    <wd-collapse v-for="item in taskList" :key="item._id" v-model="item.collapseValue" accordion custom-class="uno-m-y-[16px] uno-rounded-[8px]">
     <wd-collapse-item :name="item._id" custom-class="my-collapse-class">
      <template #title="{ expanded, disabled, isFirst }">
       <view class="uno-text-[14px] uno-flex-1">
        <view class="uno-relative uno-z-1">
         <view class="uno-text-[15px] uno-font-bold uno-flex-shrink-0 uno-text-[#333] uno-flex uno-items-center">
          <view class="uno-mr-[4px] uno-max-w-[150px] uno-overflow-hidden uno-whitespace-nowrap uno-text-ellipsis">
           {{ item.label }}
          </view>
          <!-- 如果是今日任务 显示开始的时间和结束时间  如果是周期任务 显示周期性开始时间-->
          <view class="uno-text-[12px] uno-text-[#666] uno-font-not-italic" v-if="typeFilter != 3">
           {{ showStartTimeAndEndTime(item) }}
          </view>
         </view>
         <view class="uno-text-[12px] uno-text-[#666] uno-font-not-italic" v-if="typeFilter == 3">
          {{ showStartTimeAndEndTime(item) }}
         </view>
        </view>
        <!-- 0，未开始，1，进行中， 2，已完成，3，已结束 -->
        <view class="uno-absolute uno-top-[-3px] uno-left-[-1px] uno-w-[36px] uno-h-[36px]">
         <image class="uno-w-full uno-h-full" v-if="item.status == 0" src="../../static/task-cell/un_start.png" mode="scaleToFill" />
         <image class="uno-w-full uno-h-full" v-else-if="item.status == 1" src="../../static/task-cell/starting.png" mode="scaleToFill" />
         <image class="uno-w-full uno-h-full" v-else-if="item.status == 2" src="../../static/task-cell/success.png" mode="scaleToFill" />
         <image class="uno-w-full uno-h-full" v-else-if="item.status == 3" src="../../static/task-cell/end.png" mode="scaleToFill" />
        </view>
        <view class="uno-absolute uno-top-[2px] uno-right-[7px] uno-w-[16px] uno-h-[16px]" @click.stop="updateTaskSet(item)">
         <image class="uno-w-full uno-h-full" src="../../static//task-cell/bg-setup.png" mode="scaleToFill" />
        </view>
       </view>
       <view class="uno-flex uno-items-center uno-flex-shrink-0 uno-m-l-[10px]">
        <wd-tag :type="taskTag[item.taskPriority].type" mark>{{ taskTag[item.taskPriority].label }}</wd-tag>
        <wd-icon name="arrow-down" :custom-class="`wd-collapse-item__arrow ${expanded ? 'is-retract' : ''}`" />
       </view>
      </template>
      <xlj-task-card :list="item.taskSubList" :source="item" @change="updateTaskListAction($event, item, 'server')" @update="setTaskItem(item)"></xlj-task-card>
     </wd-collapse-item>
    </wd-collapse>
   </view>
   <!-- 按钮点击新增 -->
  </scroll-view>
  <view class="edit-task-sheet">
   <wd-action-sheet v-model="setSheetShow" :actions="sheetActions" @select="selectAction" />
  </view>
 </view>
</template>

<script setup>
 import { onShow } from '@dcloudio/uni-app';
 import { onMounted, ref, watch, watchEffect, computed } from 'vue';
 import { dictMap, weekColumns, monthColumns } from '../../utils/dict';
 import { CloudFunction } from '@/utils/index';
 import dayjs from 'dayjs';
 const taskTypeOptions = dictMap.task_type;
 const collapseValue = ref([]);
 const tabValue = ref(0);
 const current = ref(0);
 const fabActive = ref(false);
 const taskList = ref([]);
 const taskTag = ref({
  1: {
   type: 'primary',
   label: '普通',
  },
  2: {
   type: 'warning',
   label: '重要',
  },
  3: {
   type: 'danger',
   label: '紧急',
  },
 });
 const tasklistQuery = ref({});
 const taskTypeFilter = ref([
  {
   label: '今日任务',
   checked: true,
   value: '1',
  },
  {
   label: '周期任务',
   value: '2',
  },
  {
   label: '定时任务',
   value: '3',
  },
 ]);
 //
 const typeFilter = computed(() => {
  return taskTypeFilter.value.filter((item) => item.checked)[0].value;
 });
 //
 watch(fabActive, () => {
  uni.navigateTo({
   url: '/pages/add-task/index',
  });
 });

 function handleAddClick() {
  console.log('我要打印的值:', 11111);
 }
 onShow(() => {
  getTaskListHandle();
 });
 //
 function tabChangeUpdateTaskList({ index }) {
  tasklistQuery.value = {};
  filterTaskType(taskTypeFilter.value[0]);
 }
 //
 function getTaskListHandle(data) {
  tasklistQuery.value = { ...tasklistQuery.value, ...data };
  console.log('我要打印的值:tasklistQuery', tasklistQuery);
  return CloudFunction('task-action', (taskAction, openid) => {
   return taskAction
    .getList({
     ...tasklistQuery.value,
     openid: openid,
    })
    .then((res) => {
     console.log('我要打印的值:111111', res);
     const { code, data = [] } = res;
     const openColl = taskList.value.map((item) => item.collapseValue).filter((item) => item);
     taskList.value = data.slice();
     if (openColl.length) {
      openColl.forEach((key) => {
       const info = taskList.value.find((item) => item._id == key);
       if (info) info.collapseValue = key;
      });
     } else if (taskList.value.length) {
      const [first] = taskList.value;
      first.collapseValue = first._id;
     }
    });
  });
 }
 //
 function updateTaskListAction($event, item, type) {
  item.taskSubList = $event;
  if (!type) return;
  return CloudFunction('task-action', (taskAction, openid) => {
   return taskAction
    .updateList({
     params: item,
     openid: openid,
    })
    .then((res) => {
     getTaskListHandle();
    });
  });
 }
 //
 function filterTaskType(item) {
  taskTypeFilter.value.forEach((item) => {
   item.checked = false;
  });
  item.checked = true;
  setTimeout(() => {
   const query = {
    taskRepeat: false,
    taskTiming: false,
   };
   const index = tabValue.value;
   query.taskType = taskTypeOptions[index].value;
   //
   if (item.value == '2') {
    query.taskRepeat = true;
   } else if (item.value == '3') {
    query.taskTiming = true;
   }
   getTaskListHandle(query);
  }, 0);
 }
 let editTaskTmp = null;
 const setSheetShow = ref(false);
 const sheetActions = ref([]);
 function selectAction(item) {
  const { index } = item;
  if (index == 0) {
   uni.navigateTo({
    url: '/pages/add-task/index?id=' + editTaskTmp._id,
   });
  } else {
   editTaskTmp.delFlag = '1';
   CloudFunction('task-action', (taskAction, openid) => {
    return taskAction
     .delete({
      params: editTaskTmp,
      openid: openid,
     })
     .then((res) => {
      getTaskListHandle();
     });
   });
  }
 }
 function updateTaskSet(item) {
  editTaskTmp = item;
  setSheetShow.value = true;
  sheetActions.value = [
   {
    name: '修改',
    color: '#1989fa',
   },
   {
    name: '删除',
    color: 'red',
   },
  ];
  const { taskRepeat } = tasklistQuery.value;
  if (taskRepeat) {
   sheetActions.value.push({
    name: item.termination ? '开启' : '终止',
    color: 'red',
   });
  }
 }
 //
 function taskPercentage(item) {
  if (!item.taskSubList) return 0;
  const total = item.taskSubList?.length || 0;
  const successTotal = item.taskSubList?.filter((item) => item.status === '1').length || 0;
  const pre = (successTotal / total) * 100;
  return pre > 10 ? pre : 10;
 }
 //
 function showStartTimeAndEndTime(item) {
  if (typeFilter.value == 1) {
   const startTime = dayjs(item.startTime).format('HH:mm');
   const endTime = dayjs(item.endTime).format('HH:mm');
   return `${startTime}-${endTime}`;
  } else if (typeFilter.value == 2) {
   return transRepeat(item);
  } else {
   return dayjs(item.startTime).format('YYYY-MM-DD HH:mm') + ' 至 ' + dayjs(item.endTime).format('YYYY-MM-DD HH:mm');
  }
 }
 //
 function transRepeat(params) {
  const startTime = dayjs(params.startTime).format('HH:mm');
  const endTime = dayjs(params.endTime).format('HH:mm');
  if (params.taskRepeat != 2) {
   const columns = params.taskRepeat == 3 ? weekColumns : monthColumns;
   const startIndex = params.taskRepeat == 3 ? dayjs(params.startTime).day() : dayjs(params.startTime).month();
   const endIndex = params.taskRepeat == 3 ? dayjs(params.startTime).day() : dayjs(params.startTime).month();
   return `${columns[startIndex]}_${startTime} 至 ${columns[endIndex]}_${endTime}`;
  } else {
   return `每日_${startTime} 至 每日_${endTime}`;
  }
 }
</script>

<style lang="scss" scoped>
 // .tab-bar-main{
 //   box-shadow: 0 0 1px 1px rgba($color: #000000, $alpha: 0.15)
 // }
 .tab-bar-item {
  color: #646566;
 }

 .tab-bar-active {
  color: #1989fa;
  font-weight: bolder;
 }
</style>
